package com.lh;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author: linghao
 * @since: 2022/10/26
 */
@Slf4j
public abstract class AbstractLogPostProcessor implements BeanPostProcessor, EnvironmentAware, BeanFactoryAware {

    private ConfigurableListableBeanFactory configurableListableBeanFactory;
    private Environment environment;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.configurableListableBeanFactory = (ConfigurableListableBeanFactory) beanFactory;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    protected  <T> List<T> getBeanOfType(Class<T> type){
        ArrayList<T> beans = new ArrayList<>(this.configurableListableBeanFactory.getBeansOfType(type).values());
        AnnotationAwareOrderComparator.sort(beans);
        Optional.ofNullable(beans).orElseGet(()->{
            log.info("list<{}> is null",type.getSimpleName());
            return new ArrayList<>();
        }).forEach((bean) ->{
            log.info("{},{}",type.getSimpleName(),bean.getClass());
        });
        return beans;
    }
}
